package com.hyf.snackbartoast.widget;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.hyf.snackbartoast.R;

/**
 * Created by Administrator on 2017/11/16.
 */

public class SnackToast {
    private Context mContext;
    private WindowManager mWm;
    private WindowManager.LayoutParams mParams;
    private View mView;

    public SnackToast(Context context) {
        mContext = context;
        initParams();
    }

    /**
     * 初始化窗体属性
     */
    private void initParams() {
        mWm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);

        mParams = new WindowManager.LayoutParams();

        mParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        mParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        mParams.type = WindowManager.LayoutParams.TYPE_TOAST;
        mParams.setTitle("Toast");
        // 设置吐司窗体的标识
        mParams.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;

        // 类型
        mParams.type = WindowManager.LayoutParams.TYPE_PHONE;

        // 透明，不透明会出现重叠效果
        mParams.format = PixelFormat.TRANSLUCENT;

        // 位置属性
        mParams.gravity = Gravity.TOP + Gravity.LEFT;  // 左上

        //出现动画
        mParams.windowAnimations = R.style.Animation_Snack_Toast;

        // 初始化吐司窗口布局
        mView = View.inflate(mContext, R.layout.layout_snack_toast, null);
    }

    public void show(String text) {
        TextView textView = mView.findViewById(R.id.hyf_tv_snack_toast);
        textView.setText(text);
        if (mView != null) {
            if (mView.getParent() != null) {
                mWm.removeView(mView);
            }
        }
        // 添加到窗体管理器中才能显示出来
        mWm.addView(mView, mParams);
    }

    public void hide() {
        if (mView != null) {
            if (mView.getParent() != null) {
                mWm.removeView(mView);
            }
        }
    }


    /**
     * 获取状态栏的高度
     * @param context
     * @return
     */
    private int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if(resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }

        return result;
    }
}
